package controller

import (
	"net/http"
	"time"

	"alolang.org.cn/api/server/config"
	"alolang.org.cn/api/server/model"
	jwt "github.com/dgrijalva/jwt-go/v4"
	"github.com/gin-gonic/gin"
)

// LoginPost - user login
func LoginPost() gin.HandlerFunc {
	return func(c *gin.Context) {
		// c.JSON(http.StatusOK, gin.H{})
		var luser model.LoginUser
		err := c.ShouldBindJSON(&luser)
		if err != nil {
			c.String(http.StatusBadRequest, "No body provided")
			return
		}
		ok, err := model.ValidateUser(luser.ID, luser.Password)
		if err != nil {
			c.String(http.StatusInternalServerError, "Login Validation Failed")
			return
		}

		if ok {
			user, _ := model.GetUserByID(luser.ID)
			j := model.NewJWT()
			claims := model.UserClaims{
				user.ID,
				user.Username,
				user.Role,
				jwt.StandardClaims{
					NotBefore: jwt.At(time.Now().Add(-1000)),                                             // 签名生效时间
					ExpiresAt: jwt.At(time.Now().Add(time.Duration(config.Server.HTTP.SessionDuration))), // 签名过期时间
					Issuer:    "alolang.org.cn",                                                          // 签名颁发者
				}}
			token, err := j.CreateToken(claims)
			if err != nil {
				c.String(http.StatusInternalServerError, "Token Generation Failed")
				return
			}
			c.String(http.StatusOK, token)
			return
		}
		c.String(http.StatusBadRequest, "Wrong Password")
	}
}

// TestLogin Temporarily generate a token without auth. ONLY FOR DEBUG
func TestLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		j := model.NewJWT()
		claims := model.UserClaims{
			1,
			"TestUser",
			1,
			jwt.StandardClaims{
				NotBefore: jwt.At(time.Now().Add(-1000)),                                             // 签名生效时间
				ExpiresAt: jwt.At(time.Now().Add(time.Duration(config.Server.HTTP.SessionDuration))), // 签名过期时间
				Issuer:    "alolang.org.cn",                                                          // 签名颁发者
			}}
		token, err := j.CreateToken(claims)
		if err != nil {
			c.String(http.StatusInternalServerError, "Token Generation Failed")
			return
		}
		c.String(http.StatusOK, token)
	}
}
